package com.chinacoal.hr.levelimpl.service.impl;


import com.chinacoal.hr.levelapi.entity.*;
import com.chinacoal.hr.levelimpl.service.*;
import com.chinacoal.hr.levelimpl.utils.StaticDicts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: YunTao.Li
 * @create: 2019-11-27 18:07
 * @description: 审批service
 **/
@Service
public class ApprovalServiceImpl implements ApprovalService {

    @Autowired
    private BizTravelService bizTravelService;

    @Autowired
    private TransPaperDetailListService transPaperDetailListService;

    @Autowired
    private AttendanceAppealService attendanceAppealService;

    // 申诉明细
    @Autowired
    private AttendanceAppealDetailService attendanceAppealDetailService;

    @Autowired
    private LeaveRecordService leaveRecordService;

    @Autowired
    private WorkflowService workflowService;

    @Autowired
    private AttendanceInfoService attendanceInfoService;


    /**
     * 获得某个出差单的信息
     *
     * @param insCode : 出差单编号
     * @return : com.chinacoal.hr.levelimpl.entity.BizTravel
     * @author : YunTao.Li
     * @date : 2019/11/27 2019/11/27
     */
    @Override
    public BizTravel getTravelInfoForApproval(String insCode) throws Throwable {
        // step1 : 首先根据出差单编号，获得出差单主表信息
        Map condition = new HashMap();
        condition.put("processInstID", insCode);
        BizTravel travel = this.bizTravelService.getBizTravelByCondition(condition);

        return travel;
    }

    /**
     * 审批通过出差申请单
     *
     * @param travelId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/11/27 2019/11/27
     */
    @Override
    @Transactional
    public Map<String, String> travelApproval(String travelId, BizTravel model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        String instanceCurrentState = model.getInstanceCurrentState();
        try {
            // step1 : 查询出待审批的BizTravel对象
            Map condition = new HashMap();
            condition.put("bizTravelId", travelId);
            BizTravel travel = this.bizTravelService.getBizTravelByCondition(condition);

            // step2 : 根据流程实例状态，修改审批状态
            this.approvalStatusChange(instanceCurrentState, travelId, travel);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 驳回出差申请单
     *
     * @param travelId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/18 2019/12/18
     */
    @Override
    public Map<String, String> travelApprovalDisagree(String travelId, BizTravel model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            // step1 : 查询出待审批的BizTravel对象
            Map condition = new HashMap();
            condition.put("bizTravelId", travelId);
            BizTravel travel = this.bizTravelService.getBizTravelByCondition(condition);

            // step2 : 完成工作项,不同意审批
//            String processInstID = travel.getInsCode();
//            String approvalContext = "测试出差审批意见：不同意";
//            String taskId = model.getTaskId();
//            workflowService.finishWorkitem(Long.parseLong(processInstID), Long.parseLong(taskId), approvalContext, WorkflowServiceImpl.WORKITEM_OPCODE_DISAGREE);

            //step3 : 修改出差申请单xip_hr_biz_travel的审批状态BUSINESS_STATUS为D已驳回
            travel.setBizTravelId(travelId);
            travel.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            this.bizTravelService.updateBizTravel(travel);

            //step4 : 修改xip_hr_pa_list员工事务单汇总表的审批状态BUSINESS_STATUS为D已驳回
            TransPaperDetailList template = new TransPaperDetailList();
            template.setPaDocId(travelId);

            TransPaperDetailList value = new TransPaperDetailList();
            value.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            value.setEffectFlag(StaticDicts.EFFECTFLAG_INVALID); // 该数据不生效

            transPaperDetailListService.updateTransPaperDetailListByTemplate(template, value);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }


    /**
     * 获得考勤申诉表信息（并填充考勤申诉明细列表到考勤申诉实体中）
     *
     * @param insCode :
     * @return : com.chinacoal.hr.levelimpl.entity.AttendanceAppeal
     * @author : YunTao.Li
     * @date : 2019/11/27 2019/11/27
     */
    @Override
    public AttendanceAppeal getAppealForApproval(String insCode) throws Throwable {
        // step1 : 首先根据出差单编号，获得考勤申诉表信息
        Map condition = new HashMap();
        condition.put("processInstID", insCode);
        AttendanceAppeal attendanceAppeal = this.attendanceAppealService.getAppealByCondition(condition);

        return attendanceAppeal;
    }

    /**
     * 考勤申诉审批
     *
     * @param explainId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/11/28 2019/11/28
     */
    @Override
    @Transactional
    public Map<String, String> appealApproval(String explainId, AttendanceAppeal model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        String instanceCurrentState = model.getInstanceCurrentState();
        try {
            // step1 : 查询待申诉的考勤申诉信息
            Map condition = new HashMap();
            condition.put("explainId", explainId);
            AttendanceAppeal attendanceAppeal = this.attendanceAppealService.getAppealByCondition(condition);
            String empCode = attendanceAppeal.getEmpCode();

            // step2 : 根据流程实例状态，修改审批状态
            this.approvalStatusChange(instanceCurrentState, explainId, attendanceAppeal);

            // step5 : 申诉通过则修改考勤明细状态
            List<AttendanceAppealDetail> attendanceAppealDetails = attendanceAppealDetailService.getAttendanceAppealDetailListByAppealId(explainId);
            for (int k = 0; k < attendanceAppealDetails.size(); k++) {
                AttendanceAppealDetail appealDetail = attendanceAppealDetails.get(k);
                Date attendDate = appealDetail.getAttendDate();
                String timeType = appealDetail.getTimeType();
                String paType = StaticDicts.HR_PA_TYPE_APPEAL;

                attendanceInfoService.attendanceInfoFixedByProcess(empCode, attendDate, timeType, paType);
            }

        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 考勤申诉审批驳回
     *
     * @param explainId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/18 2019/12/18
     */
    @Override
    public Map<String, String> appealApprovalDisagree(String explainId, AttendanceAppeal model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        try {
            // step1 : 查询待申诉的考勤申诉信息
            Map condition = new HashMap();
            condition.put("explainId", explainId);
            AttendanceAppeal attendanceAppeal = this.attendanceAppealService.getAppealByCondition(condition);

            // step2 : 完成工作项
//            String processInstID = attendanceAppeal.getInsCode();
//            String approvalContext = "测试申诉审批意见:不同意";
//            String taskId = model.getTaskId();
//            workflowService.finishWorkitem(Long.parseLong(processInstID), Long.parseLong(taskId), approvalContext, WorkflowServiceImpl.WORKITEM_OPCODE_DISAGREE);

            // step3 : 修改考勤申诉表xip_hr_kq_epl的审批状态BUSINESS_STATUS为D已驳回
            attendanceAppeal.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            this.attendanceAppealService.updateAttendanceAppeal(attendanceAppeal);

            //step4 : 修改xip_hr_pa_list员工事务单汇总表的审批状态BUSINESS_STATUS为D已驳回
            TransPaperDetailList template = new TransPaperDetailList();
            template.setPaDocId(explainId);

            TransPaperDetailList value = new TransPaperDetailList();
            value.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            value.setEffectFlag(StaticDicts.EFFECTFLAG_INVALID); //不生效

            transPaperDetailListService.updateTransPaperDetailListByTemplate(template, value);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }

        result.put("code", "1");
        return result;
    }

    /**
     * 获得请假单详情
     *
     * @param insCode : 流程实例编码
     * @return : com.chinacoal.hr.levelimpl.entity.LeaveRecord
     * @author : YunTao.Li
     * @date : 2019/11/28 2019/11/28
     */
    @Override
    public LeaveRecord getLeaveInfoFotApproval(String insCode) throws Throwable {
        Map condition = new HashMap();
        condition.put("processInstID", insCode);

        LeaveRecord leaveRecord = leaveRecordService.getLeaveRecordByCondition(condition);
        return leaveRecord;
    }

    /**
     * 审批通过请假单
     *
     * @param leaveId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/18 2019/12/18
     */
    @Override
    @Transactional
    public Map<String, String> leaveApproval(String leaveId, LeaveRecord model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");
        String instanceCurrentState = model.getInstanceCurrentState();
        try {
            // step1 : 获得待审批的请假单信息
            Map condition = new HashMap();
            condition.put("leaveId", leaveId);
            LeaveRecord leaveRecord = leaveRecordService.getLeaveRecordByCondition(condition);

            // step2 : 按当前流程实例状态修改请假单表与审批明细表的状态
            this.approvalStatusChange(instanceCurrentState, leaveId, leaveRecord);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
        result.put("code", "1");
        return result;
    }

    /**
     * 审批驳回请假单
     *
     * @param leaveId :
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author : YunTao.Li
     * @date : 2019/12/20 2019/12/20
     */
    @Override
    @Transactional
    public Map<String, String> leaveApprovalDisagree(String leaveId, LeaveRecord model) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        result.put("code", "-1");

        try {
            // step1 : 获得待审批的请假单信息
            Map condition = new HashMap();
            condition.put("leaveId", leaveId);

            LeaveRecord leaveRecord = leaveRecordService.getLeaveRecordByCondition(condition);

            // step3 : 修改考勤申诉表xip_hr_kq_epl的审批状态BUSINESS_STATUS为D已驳回
            leaveRecord.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            this.leaveRecordService.updateLeaveRecord(leaveRecord);

            //step4 : 修改xip_hr_pa_list员工事务单汇总表的审批状态BUSINESS_STATUS为D已驳回
            TransPaperDetailList template = new TransPaperDetailList();
            template.setPaDocId(leaveId);
            TransPaperDetailList value = new TransPaperDetailList();
            value.setBusinessStatus(StaticDicts.BUSINESS_STATUS_DISAGREE);
            value.setEffectFlag(StaticDicts.EFFECTFLAG_INVALID); //1不生效
            transPaperDetailListService.updateTransPaperDetailListByTemplate(template, value);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
        result.put("code", "1");
        return result;
    }

    /**
     * 查询流程实例审批历史
     *
     * @param processInstID :
     * @return : void
     * @author : YunTao.Li
     * @date : 2019/12/19 2019/12/19
     */
    @Override
    public List getApprovalHistorys(String processInstID) throws Throwable {
        return this.workflowService.getApprovalHistorys(processInstID);
    }

    /**
     * 审批时根据当前流程实例状态，修改审批状态
     *
     * @param instanceCurrentState :
     * @param paDocId              :
     * @param record               : 3种对象LeaveRecord、BizTravel、AttendanceAppeal
     * @return : void
     * @author : YunTao.Li
     * @date : 2020/8/6 2020/8/6
     */
    private void approvalStatusChange(String instanceCurrentState, String paDocId, Object record) throws Throwable {

        TransPaperDetailList template = new TransPaperDetailList();
        TransPaperDetailList value = new TransPaperDetailList();

        if (StaticDicts.PROCESS_INST_STATE_FINISHED.equals(instanceCurrentState)) {
            // 修改请假单表xip_hr_leave| xip_hr_pa_list员工事务单汇总表的审批状态BUSINESS_STATUS为E已审批
            record.getClass().getMethod("setBusinessStatus", String.class).invoke(record, StaticDicts.BUSINESS_STATUS_APPROVALED);
            value.setBusinessStatus(StaticDicts.BUSINESS_STATUS_APPROVALED);
        } else {
            // 修改请假单表xip_hr_leave| xip_hr_pa_list员工事务单汇总表的审批状态BUSINESS_STATUS为F审批中
            record.getClass().getMethod("setBusinessStatus", String.class).invoke(record, StaticDicts.BUSINESS_STATUS_APPROVING);
            value.setBusinessStatus(StaticDicts.BUSINESS_STATUS_APPROVING);
        }

        template.setPaDocId(paDocId);
        value.setEffectFlag(StaticDicts.EFFECTFLAG_INVALID); //1 未生效
        transPaperDetailListService.updateTransPaperDetailListByTemplate(template, value);

        if (record instanceof LeaveRecord) {

            this.leaveRecordService.updateLeaveRecord((LeaveRecord) record);
        } else if (record instanceof AttendanceAppeal) {

            this.attendanceAppealService.updateAttendanceAppeal((AttendanceAppeal) record);
        } else if (record instanceof BizTravel) {

            this.bizTravelService.updateBizTravel((BizTravel) record);
        } else {
            throw new Exception("位置的对象类型");
        }

    }
}
